﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Utils
{
    /// <summary>
    /// 异或+16进制加密/解密算法
    /// </summary>
    public class XorHexHelper
    {
        private const string KEY = "JJUTILS1234567809"; // 密钥
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public static string Encrypt(string txt,string key="")
        {
#if Standard
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
#endif
            StringBuilder sb = new StringBuilder();
            byte[] bs = System.Text.Encoding.Default.GetBytes(txt); // 原字符串转换成字节数组
            if (string.IsNullOrEmpty(key)) key = KEY;
            byte[] keys = System.Text.Encoding.Default.GetBytes(key); // 密钥转换成字节数组

            // 异或
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = (byte)(bs[i] ^ keys[i % keys.Length]);
            }

            // 编码成16进制数组
            foreach (byte b in bs)
            {
                sb.AppendFormat("{0:x2}", b);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public static string Decrypt(string txt,string key="")
        {
#if Standard
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
#endif
            int len = txt.Length;
            byte[] bs = new byte[len / 2];

            // 16进制数组转换会byte数组
            for (int i = 0; i < len / 2; i++)
            {
                bs[i] = (byte)(Convert.ToInt32(txt.Substring(i * 2, 2), 16));
            }
            if (string.IsNullOrEmpty(key)) key = KEY;
            byte[] keys = System.Text.Encoding.Default.GetBytes(key); // 密钥转换成字节数组

            // 异或
            for (int i = 0; i < bs.Length; i++)
            {
                bs[i] = (byte)(bs[i] ^ keys[i % keys.Length]);
            }

            // byte数组还原成字符串
            return System.Text.Encoding.Default.GetString(bs);
        }

    }
}
